package com.wc.community.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wc.community.Util.SSLUtil;
import com.wc.community.dto.AccessTokenDTO;
import com.wc.community.dto.GitUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * @author wc
 * @create 2021-06-17-10:01
 * @desc
 */
@Component
public class GitProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDTO) throws KeyManagementException, NoSuchAlgorithmException {
        MediaType mediaType
                = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = SSLUtil.getUnsafeOkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" +
                        accessTokenDTO.getCode() + "&client_id=" + accessTokenDTO.getClientId() +
                        "&redirect_uri=" + accessTokenDTO.getRedirectUri() + "&client_secret=" +
                        accessTokenDTO.getClientSecret())
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            System.out.println(string);
            JSONObject obj=JSONObject.parseObject(string);
            return obj.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public GitUser getUser(String accessToken) throws KeyManagementException, NoSuchAlgorithmException {
        OkHttpClient client = SSLUtil.getUnsafeOkHttpClient();
        Request request = new Request.Builder()
                .url("http://api.gitee.com/api/v5/user?access_token=" + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GitUser gitUser = JSON.parseObject(string, GitUser.class);
            System.out.println(gitUser.toString());
            return gitUser;
        } catch (IOException e) {
            System.out.println("111");
        }
        return null;
    }
}
